import { subStringAndReplaceName } from '../tool/tool';

let readWaitingNodeId = ''; //节点名称ID

/**
 * This handler retrieves the images from the clipboard as a base64 string and returns it in a callback.
 *
 * @param pasteEvent
 * @param callback
 */
export function retrieveImageFromClipboardAsBase64(pasteEvent, callback, imageFormat) {
	if (pasteEvent.clipboardData == false) {
		if (typeof callback == 'function') {
			callback(undefined);
		}
	}

	var items = pasteEvent.clipboardData.items;

	if (items == undefined) {
		if (typeof callback == 'function') {
			callback(undefined);
		}
	}

	for (var i = 0; i < items.length; i++) {
		// Skip content if not image
		if (items[i].type.indexOf('image') == -1) continue;
		// Retrieve image on clipboard as blob
		var blob = items[i].getAsFile();

		// Create an abstract canvas and get context
		var mycanvas = document.createElement('canvas');
		var ctx = mycanvas.getContext('2d');

		// Create an image
		var img = new Image();

		// Once the image loads, render the img on the canvas
		img.onload = function() {
			// Update dimensions of the canvas with the dimensions of the image
			mycanvas.width = this.width;
			mycanvas.height = this.height;

			// Draw the image
			ctx.drawImage(img, 0, 0);

			// Execute callback with the base64 URI of the image
			if (typeof callback == 'function') {
				callback(mycanvas.toDataURL(imageFormat || 'image/png'));
			}
		};

		// Crossbrowser support for URL
		var URLObj = window.URL || window.webkitURL;

		// Creates a DOMString containing a URL representing the object given in the parameter
		// namely the original Blob
		img.src = URLObj.createObjectURL(blob);
	}
}

export function dealWithBigBase64Image(base64, w, callback, maxSize, minSize) {
	var newImage = new Image();
	var quality = 0.6;
	newImage.src = base64;
	var imgWidth, imgHeight;
	newImage.onload = function() {
		imgWidth = this.width;
		imgHeight = this.height;
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		if (Math.max(imgWidth, imgHeight) > w) {
			if (imgWidth > imgHeight) {
				canvas.width = w;
				canvas.height = (w * imgHeight) / imgWidth;
			} else {
				canvas.height = w;
				canvas.width = (w * imgWidth) / imgHeight;
			}
		} else {
			canvas.width = imgWidth;
			canvas.height = imgHeight;
			quality = 0.6;
		}
		ctx.clearRect(0, 0, canvas.width, canvas.height);
		ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
		var base64 = canvas.toDataURL('image/jpeg', quality);
		while (base64.length / 1024 > maxSize) {
			quality -= 0.01;
			base64 = canvas.toDataURL('image/jpeg', quality);
		}
		while (base64.length / 1024 < minSize) {
			quality += 0.01;
			base64 = canvas.toDataURL('image/jpeg', quality);
		}
		callback(base64);
	};
}

export function getBrowserClinetInfo() {
	var Sys = {};
	var ua = navigator.userAgent.toLowerCase();
	var re = /(msie|firefox|chrome|opera|version).*?([\d.]+)/;
	var m = ua.match(re);
	try {
		Sys.type = m[1].replace(/version/, 'safari');
		Sys.version = m[2];
	} catch (e) {
		Sys.type = 'unknown';
		Sys.version = 'unknown';
	}
	return Sys;
}

export class ZBase64 {
	// private property
	constructor() {
		this._keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
	}

	set keyStr(val) {
		this._keyStr = val;
	}

	get keyStr() {
		this._keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
		return this._keyStr;
	}
	// _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

	// public method for encoding
	encode(input) {
		var output = '';
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = this._utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			console.log(enc1);
			console.log(this._keyStr);
			console.log(this._keyStr.charAt(enc1));
			output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
		}
		return output;
	}

	// public method for decoding
	decode(input) {
		var output = '';
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		// eslint-disable-next-line no-useless-escape
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
		while (i < input.length) {
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = this._utf8_decode(output);
		return output;
	}

	// private method for UTF-8 encoding
	_utf8_encode(string) {
		string = string.replace(/\r\n/g, '\n');
		var utftext = '';
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if (c > 127 && c < 2048) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	}

	// private method for UTF-8 decoding
	_utf8_decode(utftext) {
		var string = '';
		var i = 0;
		var c = 0;
		// var c1 = 0;
		var c2 = 0;
		var c3 = 0;
		// var c = c1 = c2 = 0;
		while (i < utftext.length) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if (c > 191 && c < 224) {
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
}

export function base64ToFile(base64, fileName) {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	var blob = new Blob([u8arr], {
		type: mime
	});
	blob.lastModifiedDate = new Date();
	blob.name = fileName;
	console.log('functionbase64ToFile -> blob', blob); // file
	return blob;
}

/** 2021-11-19 utils 新增节流方法 */

/**
 * 节流函数
 * @param { Function } callback 回调函数
 * @param { Number } time 等待时长
 * @returns
 */
export function throttle(callback, wait) {
	// 定义开始时间
	let start = 0;
	// 返回结果
	return function() {
		// 获取当前的时间戳
		let now = Date.now();
		if (now - start >= wait) {
			// 满足条件，执行回调函数
			callback.apply(this, arguments);
			start = now;
		}
	};
}

/**
 * 防抖函数
 * @param { Fucntion } callback  回调函数
 * @param {*} time 时长
 * @returns
 */
export function debounce(callback, time) {
	// 声明一个 timerId 用来存储定时器
	let timerId = null;
	return function() {
		// 判断 timerId 是否存在, 存在则清除
		if (timerId) {
			clearTimeout(timerId);
		}
		timerId = setTimeout(() => {
			callback.apply(this, arguments);
			// 重置定时器变量
			timerId = null;
		}, time);
	};
}

/**
 *
 * @param { Object } agent 坐席数据
 * @returns { Object } 消息体
 */
export function agentInSessionRecord(agent) {
	let message = {};
	message.type = 'text';
	message.id = '';
	message.date = agent.at;
	message.from = 'stytem';
	message.label = 'system';
	message.fromUser = {
		id: '',
		name: '系统消息',
		avatar: ''
	};
	message.data = `坐席 ${agent.user.name} ${getAgentStatus(agent.status)}`;
	return message;
}

/**
 *
 * @param { String } status 坐席状态
 * @returns
 */
export function getAgentStatus(status) {
	let result = '';
	switch (status) {
		case 'joined':
			result = '加入会话';
			break;
		case 'quit':
			result = '离开会话';
			break;
		default:
			result = '';
			break;
	}
	return result;
}

export function sendMessageToRecord(type, msg, user) {
	type = type ? type : 'text';
	let message = {};
	message.type = type;
	message.id = user.clientId || '';
	message.date = getCurrentDate(msg.createdAt);
	message.from = user.id;
	message.label = user.role;
	message.fromUser = {
		id: user.id,
		name: user.userName,
		avatar: user.picture,
		isRobot: user.isRobot
	};
	message.data = formatMessage(type, msg, user);

	return message;
}

/**
 *
 * @param { Date } sourceTime 源时间
 * @returns 新时间
 */
export function formatMessageTime(sourceTime) {
	let date = new Date(sourceTime).Format('yyyy/MM/dd');
	let time = new Date(sourceTime).Format('hh:mm:ss');
	let hour = new Date(sourceTime).getHours();
	let result = date + ' ' + (hour < 12 ? '上午' : '下午') + ' ' + time;
	return result;
}

/**
 * 格式化消息
 * @param { String } type 消息类型
 * @param { Object } msg 消息体
 * @returns 格式化后消息体
 */
export function formatMessage(type, msg, user) {
	let result = '';
	switch (type) {
		case 'text':
			result = msg.text ? msg.text : msg;
			break;
		case 'link':
			result = { type: msg.type, url: msg.url, fileName: msg.fileName, name: msg.name, suffix: msg.suffix, size: msg.size || '' };
			break;
		case 'hold-on':
			result = { type: msg.data.transferInfo.type, contents: `${msg.data.transferInfo.type === 'transfer-bizscenario' ? '发起了场景转接到 < ' + msg.data.transferInfo.bizSceneName + ' >' : '转人工'}` };
			break;
		case 'sound-reception':
			result = { type: msg.data.modType, contents: `发起模板收音` };
			break;
		default:
			result = formatBusinessMessage(type, msg, user);
			break;
	}
	return result;
}

/**
 * 格式化业务指令消息
 * @param { String } type 消息类型
 * @param { Object } msg 消息体
 * @returns 格式化后消息体
 */
export function formatBusinessMessage(type, msg, user) {
	let result = '';
	if (user.role === 'agent' && !msg.data.status) {
		switch (msg.data.cmd) {
			case 'view':
				if (type === 'peer-cancel') {
					if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.nodeType && msg.data.data.nodeType === 'waitingReadNode' && msg.data.data.type === 'messageSummary') {
						result = { type: msg.data.type, contents: `超时未确认<${readWaitingNodeId}>汇总内容` };
					} else if (msg.data.data.type === 'scanCode' && msg.data.data.nodeType === 'waitingReadNode') {
						let code = msg && msg.data && msg.data.data && msg.data.data.data && msg.data.data.data.data.code ? msg.data.data.data.data.code : '';
						result = { type: msg.data.type, contents: `您超时未确认查阅<${readWaitingNodeId}>存储内容${code}，已自动执行下一步操作` };
					} else {
						result = { type: msg.data.type, contents: `超时未查阅` };
					}
				} else if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.nodeType && msg.data.data.type === 'messageSummary' && msg.data.data.nodeType === 'waitingReadNode') {
					readWaitingNodeId = subStringAndReplaceName(msg.data.data.id, '_', 'messageSummary', '信息汇总');
					result = { type: msg.data.type, contents: `展示<${readWaitingNodeId}>汇总内容` };
				} else if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.nodeType && msg.data.data.type === 'messageSummary' && msg.data.data.nodeType === 'messageSummary') {
					result = { type: msg.data.type, contents: `发起信息汇总` };
				} else if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.nodeType && msg.data.data.type === 'scanCode' && msg.data.data.nodeType === 'waitingReadNode') {
					readWaitingNodeId = subStringAndReplaceName(msg.data.data.id, '_', 'scanCode', '推送扫码');
					result = { type: msg.data.type, contents: `展示<${readWaitingNodeId}>存储内容${msg.data.data.data.code}` };
				} else if (msg && msg.data && msg.data.data && msg.data.data.type && msg.data.data.type === 'richtext' && msg.data.data.data && msg.data.data.data.content) {
					result = { type: msg.data.data.type, content: msg.data.data.data.content };
				} else {
					result = { type: msg.data.type, url: msg.data.data.url || msg.data.data.code, fileName: msg.data.data.name || msg.data.data.code || '' };
				}
				break;
			case 'show-guide-box':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '取消引导框' : '推送引导框'}` };
				break;
			case 'get-screenshot':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '取消截图' : '请求截图'}` };
				break;
			case 'get-handwriting':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '取消签名' : '邀请签名'}` };
				break;
			case 'scan-code':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '取消扫码' : '请求扫码'}` };
				break;
			case 'get-geo-location':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '取消获取地理位置' : '请求获取地理位置'}` };
				break;
			case 'fill-form':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '终止推送表单' : '推送表单'}` };
				break;
			case 'confirm':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '取消汇总确认' : '推送汇总确认'}` };
				break;
			case 'make-choice':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '取消选项判断' : '推送选项判断'}` };
				break;
			case 'screen-mark':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '取消共享标注' : '请求共享标注'}` };
				break;
			case 'third-nlp':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '' : '进行对接外部NLP'}` };
				break;
			case 'screen-share':
				result = { type: msg.data.cmd, contents: `${type === 'peer-cancel' ? '取消屏幕共享' : '发起屏幕共享'}` };
				break;
			default:
				result = msg;
				break;
		}
	} else {
		if (msg.data.cmd === 'show-guide-box') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意推送引导框` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝推送引导框` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `推送引导框失败` };
					break;
				case 'done':
					result = { type: msg.data.cmd, contents: `` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (msg.data.cmd === 'get-screenshot') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意截图` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝截图` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '正在截图' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `截图失败` };
					break;
				case 'done':
					result = { type: 'pic', status: msg.data.status, url: msg.data.result.url, fileName: msg.data.result.fileName || '' };
					break;
				default:
					result = msg;
					break;
			}
		} else if (msg.data.cmd === 'get-handwriting') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意签名` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝签名` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `签名失败` };
					break;
				case 'done':
					result = { type: 'pic', status: msg.data.status, url: msg.data.result.url, fileName: msg.data.result.fileName || '' };
					break;
				default:
					result = msg;
					break;
			}
		} else if (msg.data.cmd === 'scan-code') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意扫码` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝扫码` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '正在扫码' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `扫码失败` };
					break;
				case 'done':
					result = { type: msg.data.cmd, status: msg.data.status, contents: `扫码成功，${msg.data.result.type === 'bar-code' ? '条形码：' : '二维码连接:'}${msg.data.result.code}` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (msg.data.cmd === 'get-geo-location') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意获取地理位置` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝获取地理位置` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '正在获取地理位置' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `获取地理位置失败` };
					break;
				case 'done':
					result = { type: msg.data.cmd, status: msg.data.status, contents: `获取成功，${msg.data.result.address || ''}` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (msg.data.cmd === 'fill-form') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意填写表单` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝填写表单` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '正在填写表单' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `填写表单失败` };
					break;
				case 'done':
					result = { type: msg.data.cmd, status: msg.data.status, contents: `提交表单 <${msg.data.result.formName}> 成功` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (msg.data.cmd === 'confirm') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意汇总确认` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝汇总确认` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '正在汇总确认' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `汇总确认失败` };
					break;
				case 'done':
					result = { type: msg.data.cmd, contents: `汇总确认完成` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (msg.data.cmd === 'make-choice') {
			switch (msg.data.status) {
				case 'accepted':
					result = { type: msg.data.cmd, contents: `同意选项判断` };
					break;
				case 'rejected':
					result = { type: msg.data.cmd, contents: `拒绝选项判断` };
					break;
				case 'in-progress':
					result = { type: msg.data.cmd, contents: '正在选项判断' };
					break;
				case 'failed':
					result = { type: msg.data.cmd, contents: `选项判断确认失败` };
					break;
				case 'done':
					result = { type: msg.data.cmd, contents: `选项判断确认完成` };
					break;
				default:
					result = msg;
					break;
			}
		} else if (msg && msg.data && msg.data.cmd && msg.data.result && msg.data.result.nodeType && msg.data.cmd === 'view' && msg.data.result.nodeType === 'waitingReadNode') {
			switch (msg.data.status) {
				case 'rejected':
					result = { type: msg.data.cmd, contents: `不确认<${readWaitingNodeId}>汇总内容` };
					break;
				case 'done':
					if (msg && msg.data && msg.data.result && msg.data.result.type && msg.data.result.type === 'messageSummary') {
						result = { type: msg.data.cmd, contents: `确认<${readWaitingNodeId}>汇总内容` };
					} else {
						let code = msg && msg.data && msg.data.result && msg.data.result.code ? msg.data.result.code : '';
						result = { type: msg.data.cmd, contents: `已确认查阅<${readWaitingNodeId}>存储内容${code}` };
					}
					break;
				default:
					break;
			}
		}
	}
	return result;
}

export function getCurrentDate(date) {
	date = date ? formatMessageTime(date) : formatMessageTime(new Date());
	return date;
}

export function getMessageStatus(msg) {
	let result = '';
	switch (msg.data.cmd) {
		case 'show-guide-box':
			result = '推送引导框';
			break;
		case 'get-screenshot':
			result = '';
			break;
		case 'get-handwriting':
			result = '';
			break;
		case 'scan-code':
			result = '';
			break;
		case 'get-geo-location':
			result = '';
			break;
		case 'fill-form':
			result = '';
			break;
		case 'confirm':
			result = '';
			break;
		case 'make-choice':
			result = '';
			break;
		default:
			result = msg;
			break;
	}
	return result;
}

/**
 * 筛选会话中坐席信息数据
 * @param { Array } members
 * @returns 筛选过后的坐席数组
 */
export function filterAgentMember(members) {
	let agentMembers = members
		.filter(item => item.role === 'agent')
		.map(agent => {
			return {
				date: agent.at,
				clientId: agent.id,
				role: agent.role,
				id: agent.user.id,
				userName: agent.user.name,
				org: agent.user.org,
				isRobot: agent.user.profile && agent.user.profile.isRobot ? agent.user.profile.isRobot : false,
				picture: agent.picture ? agent.picture : ''
			};
		});
	return agentMembers;
}
// 根据消息 from，筛选坐席信息
export function filterAgentByMsg(from, members) {
	return members.find(agent => agent.clientId === from);
}
